package com.wyp168.socket.tcp.socketDemo03;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

public class Client {
    public static void main(String[] args) throws Exception{
        //连接到当前主机的9001端口服务
        Socket socket = new Socket(InetAddress.getLocalHost(), 9001);
        //获取数据通道的输出流对象
        OutputStream outputStream = socket.getOutputStream();
        //通过转换流OutputStreamWriter 将字节流对象转换成字符流对象
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
        //向字符流中添加内容
        bufferedWriter.write("hello server, 你好");
        //向字符流末尾插入一个空行
        bufferedWriter.newLine();
        bufferedWriter.flush(); //如果使用字符流，需要手动刷新，否则数据不会写入到数据 通道中

        InputStream inputStream = socket.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String s = "";
        while ((s = bufferedReader.readLine()) != null) {
            System.out.println(s);
        }


        //资源关闭
        outputStream.close();
        inputStream.close();
        bufferedReader.close();
        bufferedWriter.close();
        socket.close();
    }
}
